import type { GenerateServiceProps } from 'openapi-ts-request';
import { join } from 'path';

export default [
  {
    schemaPath: 'http://127.0.0.1:4523/export/openapi/3?version=3.0',
    serversPath: './src/api/user_test',
    requestLibPath: `import { request } from '@/utils/http/request';
                    import type { AxiosRequestConfig } from 'axios';
                    import type { RequestOptions as RequestOptionsType } from '/#/axios';
                    type RequestOptions = RequestOptionsType & AxiosRequestConfig;
                    `,
    requestOptionsType: 'RequestOptions',
    isGenReactQuery: true,
    reactQueryMode: 'vue',
    isGenJavaScript: false,
    isDisplayTypeLabel: true,
    enableLogging: true,
    templatesFolder: './templates/openapi-enhanced',

    // 使用hook自定义生成逻辑
    hook: {
      // 自定义函数名生成
      customFunctionName: (apiData) => {
        // 获取原始函数名
        let name = apiData.operationId || '';

        // 如果没有operationId，从path和method构建一个
        if (!name || name.trim() === '') {
          console.log('警告: 发现缺少operationId的API:', apiData.path, apiData.method);

          // 从路径构建函数名
          const pathParts = apiData.path.split('/').filter(Boolean);
          // 移除API前缀
          if (pathParts[0] === 'api') pathParts.shift();

          // 使用路径的最后两部分
          const resourceName = pathParts.length > 1 ? pathParts[pathParts.length - 2] : 'api';
          const actionName = pathParts[pathParts.length - 1] || 'default';

          const method = apiData.method.toLowerCase();
          let methodPrefix = '';

          // 根据HTTP方法和路径智能推断前缀
          if (method === 'get') {
            methodPrefix = 'get';
          } else if (method === 'post') {
            // POST方法需要进一步分析路径和操作
            const pathLower = apiData.path.toLowerCase();
            if (
              pathLower.includes('create') ||
              pathLower.includes('add') ||
              pathLower.includes('save')
            ) {
              methodPrefix = 'create';
            } else if (
              pathLower.includes('query') ||
              pathLower.includes('search') ||
              pathLower.includes('list') ||
              pathLower.includes('page')
            ) {
              methodPrefix = 'query';
            } else if (pathLower.includes('update') || pathLower.includes('modify')) {
              methodPrefix = 'update';
            } else {
              // 默认使用submit作为通用前缀
              methodPrefix = 'submit';
            }
          } else if (method === 'put') {
            methodPrefix = 'update';
          } else if (method === 'delete') {
            methodPrefix = 'delete';
          }

          name = `${methodPrefix}${resourceName.charAt(0).toUpperCase() + resourceName.slice(1)}${actionName.charAt(0).toUpperCase() + actionName.slice(1)}`;
          return name;
        }

        // 移除通用前缀和后缀
        name = name.replace(/^api/, '');
        name = name.replace(/Using(Get|Post|Put|Delete)$/, '');

        // 检测是否包含中文拼音片段（通用处理，无需硬编码特定API路径）
        const containsChinesePinyin = (str) => {
          // 常见的中文拼音模式：多个连续的小写字母组合
          const pinyinPattern = /[a-z]{4,}/g;
          const matches = str.match(pinyinPattern) || [];

          // 判断是否存在较长的连续小写字母（可能是拼音）
          return matches.some((match) => match.length >= 5);
        };

        // 如果函数名可能包含中文拼音，尝试从路径构建更好的名称
        if (containsChinesePinyin(name) || name.length > 30) {
          // 从路径构建更简洁的函数名
          const pathParts = apiData.path.split('/').filter(Boolean);
          if (pathParts[0] === 'api') pathParts.shift();

          const method = apiData.method.toLowerCase();
          let methodPrefix = '';

          // 根据HTTP方法和路径智能推断前缀
          if (method === 'get') {
            methodPrefix = 'get';
          } else if (method === 'post') {
            // POST方法需要进一步分析路径和操作
            const pathLower = apiData.path.toLowerCase();
            if (pathLower.includes('create') || pathLower.includes('add')) {
              methodPrefix = 'create';
            } else if (pathLower.includes('query') || pathLower.includes('search')) {
              methodPrefix = 'query';
            } else if (pathLower.includes('update') || pathLower.includes('modify')) {
              methodPrefix = 'update';
            } else {
              // 默认使用submit作为通用前缀
              methodPrefix = 'submit';
            }
          } else if (method === 'put') {
            methodPrefix = 'update';
          } else if (method === 'delete') {
            methodPrefix = 'delete';
          }

          // 使用最后两段路径
          if (pathParts.length >= 2) {
            const resource = pathParts[pathParts.length - 2];
            const action = pathParts[pathParts.length - 1];
            name = `${methodPrefix}${resource.charAt(0).toUpperCase() + resource.slice(1)}${action.charAt(0).toUpperCase() + action.slice(1)}`;
          } else if (pathParts.length === 1) {
            const action = pathParts[0];
            name = `${methodPrefix}${action.charAt(0).toUpperCase() + action.slice(1)}`;
          }
        }

        // 确保函数名是有效的JavaScript标识符
        if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {
          console.log('警告: 生成的函数名无效:', name, '对应路径:', apiData.path);
          // 替换非法字符
          name = name.replace(/[^a-zA-Z0-9_$]/g, '').replace(/^[^a-zA-Z_$]/, '_');
          // 如果仍然无效，使用安全的默认名称
          if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {
            name = `api${apiData.method.toLowerCase()}`;
          }
        }

        // 确保函数名不为空
        if (!name || name.trim() === '') {
          name = `api${apiData.method.toLowerCase()}${Date.now()}`;
        }

        return name;
      },

      // 自定义文件名生成
      customFileNames: (operationObject, apiPath, apiMethod) => {
        // 处理空路径的情况
        if (!apiPath) {
          console.log('警告: 发现空路径API');
          return ['defaultService'];
        }

        // 通用的文件名分组逻辑，无需硬编码特定路径
        const pathSegments = apiPath.split('/').filter(Boolean);

        // 跳过通用前缀，如api
        if (pathSegments[0] === 'api' && pathSegments.length > 1) {
          const moduleName = pathSegments[1].toLowerCase();
          return [`${moduleName}Service`];
        }

        // 如果有分组信息，使用第一段路径作为分组
        if (pathSegments.length > 0) {
          const moduleName = pathSegments[0].toLowerCase();
          return [`${moduleName}Service`];
        }

        // 默认文件名
        return ['apiService'];
      },
    },

    // 添加模型名称前缀，避免类型命名冲突
    namespace: 'API',
  },
] as GenerateServiceProps[];
